import type { PageDto, PageData, PostDto, PostRes, PutDto, PutRes, DisableDto, DisableRes, PutMutiDto, PutMutiRes } from "~/rest";
import { WithPasterList, WithStockTotal } from "~/view.with";
import { Tradable } from "~/extend";

import { Gateway, getGateway } from "@/droplet-bus/core.define";
import { Contact } from "@/pond-contact/schema.contact";
import { BookSortable } from "@/pond-book/core.define";

import { RiverTonGateway } from "@/river-ton/core.define";
import { TonOrder, TonOrderGroup } from "@/river-ton/schema.order";
import { NotchSortable } from "@/river-stock/core.define";
import { Media } from "@/pond-media/schema.media";
import { User } from "@/stream-user/schema.user";

type getTonOrderComDto = PageDto<TonOrder> & { groupId: TonOrderGroup["id"]; decimal: number };

export const TonOrderGroupGateway: Gateway = getGateway(RiverTonGateway, "river_ton_order_group");
export type putTonOrderGroupDto = PutMutiDto<TonOrderGroup>;
export type deleteTonOrderGroupDto = DisableDto;

export interface TonOrderGroupInterfaceWithPrimary<T> {
  get(dto: T): Promise<PageData<TonOrderGroup>>;
  putSync(dto: T & putTonOrderGroupDto): Promise<PutMutiRes<TonOrderGroup>>;
  disable(dto: T & deleteTonOrderGroupDto): Promise<DisableRes>;
}

export const TonOrderGateway: Gateway = getGateway(RiverTonGateway, "river_ton_order");
export type getTonOrderDto = getTonOrderComDto;

export type getOrderByTradeIdDto = { tradeIDs: Tradable["tradeId"][] };
export type getOrderAfterBookSortDto = getTonOrderComDto & BookSortable;
export type getOrderAfterNotchSortDto = getTonOrderComDto & NotchSortable;

export interface TonOrderReadInterfaceWithGrant<T> {
  /** 查询订单 */
  get(dto: T & getTonOrderDto): Promise<PageData<WithPasterList & TonOrder & WithStockTotal>>;

  /** 根据交易号查询订单 */
  getOrderByTradeId(dto: T & getOrderByTradeIdDto): Promise<PageData<WithPasterList & TonOrder>>;

  /** 根据账簿金额进行排序 */
  getOrderAfterBookSort(dto: T & getOrderAfterBookSortDto): Promise<PageData<WithPasterList & TonOrder>>;

  /** 根据库存重量进行排序 */
  getOrderAfterNotchSort(dto: T & getOrderAfterNotchSortDto): Promise<PageData<WithPasterList & TonOrder & WithStockTotal>>;
}

export type postTonOrderDto = PostDto<TonOrder> & { groupId: TonOrderGroup["id"]; contactId: Contact["id"] };
export type putTonOrderDto = PutDto<TonOrder>;
export type doBackupTonOrderDto = { orderGroupId: TonOrderGroup["id"]; tradeYear: number; tradeMonth: number; creatorId?: User["uuid32"] };

export interface TonOrderWriteInterfaceWithGrant<T> {
  /** 创建新订单 */
  postSync(dto: T & postTonOrderDto): Promise<PostRes<TonOrder>>;

  /** 修改订单 */
  put(dto: T & putTonOrderDto): Promise<PutRes<TonOrder>>;

  /** 订单备份 */
  doBackup(dto: T & doBackupTonOrderDto): Promise<{ media: Media }>;
}
